package com.zxl.web.controller;

import com.zxl.pojo.FileInfo;
import org.aspectj.util.FileUtil;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class FileController {

    @PostMapping
    public FileInfo upload(MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        File localFile = new File("/", System.currentTimeMillis() + ".txt");
        file.transferTo(localFile);
        FileInfo fileInfo = new FileInfo();
        return fileInfo;
    }

    @GetMapping("{id}")
    public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
        File downFile = new File("/", id + ".txt");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.addHeader("Content-Disposition", "attachment;filename=test.txt");
        FileUtil.copyStream(new FileInputStream(downFile), response.getOutputStream());
    }
}
